﻿using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;
using WebShop.Contracts;
using WebShop.DAL;
using WebShop.DAL.Interfaces;
using WebShop.DAL.Repositories;
using WebShop.Infrastructure;
using WebShop.Models;

namespace WebShop
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters, IUnityContainer container)
        {
            //filters.Add(new HandleErrorAttribute());           
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Categories", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            //Configure for Dependency Injection using Unity
            // TODO: move it in web config
            UnityContainer container = new UnityContainer();
            container.RegisterType<IProductRepository, ProductRepository>(new HttpContextLifetimeManager<IProductRepository>());
            container.RegisterType<ICategoryRepository, CategoryReository>(new HttpContextLifetimeManager<ICategoryRepository>());
            container.RegisterType<IShipperRepository, ShipperRepository>(new HttpContextLifetimeManager<IShipperRepository>());
            container.RegisterType<ISupplierRepository, SupplierRepository>(new HttpContextLifetimeManager<ISupplierRepository>());
            container.RegisterType<IUserRepository, UserRepository>(new HttpContextLifetimeManager<IUserRepository>());
            container.RegisterType<IOrderRepository, OrderRepository>(new HttpContextLifetimeManager<IOrderRepository>());
            container.RegisterType<IRoleRepository, RoleRepository>(new HttpContextLifetimeManager<IRoleRepository>());
            container.RegisterType<IProductsCartRepository, ProductsCartRepository>(new HttpContextLifetimeManager<IProductsCartRepository>());
            container.RegisterType<ILogRepository, LogRepository>();
            container.RegisterType<ILogRepository, LogRepository>(new SingletonLifetimeManager<ILogRepository>());
            container.Resolve<ILogRepository>();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            RegisterGlobalFilters(GlobalFilters.Filters, container);
            RegisterRoutes(RouteTable.Routes);

            ModelBinders.Binders.Add(typeof(Category), new ImageModelBinder("Picture"));
            ModelBinders.Binders.Add(typeof(decimal?), new DecimalModelBinder());
        }
    }
}